import axios from 'axios'
import Qs from 'qs'
import {BASE_URL} from './config'

// 错误状态与提示
const errCode = {
  400: '',
  401: '未登录，请先登录',
  413: '请求实体过大',
  404: '',
  500: ''
}

function errToast(code, fn) {
  // todo: 讲alert替换成自定义错误弹窗
  alert(errCode[code], 1.5, fn)
}

// axios默认配置
axios.defaults.timeout = 25000
axios.defaults.baseURL = BASE_URL
axios.defaults.transformRequest = function (data) {
  data = Qs.stringify(data)
  return data
}

// 请求拦截
axios.interceptors.request.use(
  config => {
    if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
      config.headers['Accept'] = 'application/json, text/javascript, */*; q=0.01'
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    // 统一指定语言类型，默认英文
    config.headers['lang'] = localStorage.lang || 'zh_CN'
    config.headers['X-Token'] = localStorage.token || ''
    return config
  },
  err => {
    return Promise.reject(err)
  })

// 路由响应拦截
axios.interceptors.response.use(
  res => {
    let data = res.data
    if (data.meta) {
      if (data.code === 0) {
        return data
      }
      if (data.meta.code === '00') {
        return data
      } else {

        return data
      }
    } else {
      return data
    }
  },
  error => {
    if (error && error.response) {
      console.log('网络故障')
      switch (error.response.status) {
        case 400:
          errToast(error.response.status)
          break
        case 401:
          errToast(error.response.status, () => {
            window.location.hash = '/login'
            localStorage.clear()
          })
          break
        case 404:
          errToast(error.response.status)
          break
        case 413:
          errToast(error.response.status)
          break
        case 500:
          errToast(error.response.status)
          break
        default:
          break
      }
    }
    return Promise.reject(error)
  })

export default axios
